package com.iocup.keybastion.authentication.authenticator;



import com.iocup.keybastion.authentication.userdetails.UserDetails;
import com.iocup.keybastion.common.AuthConstant;
import com.iocup.keybastion.context.WebContextHolder;
import com.pine.sunflower.core.utils.JsonUtils;

import java.util.Map;
import java.util.Optional;

/**
 *  默认的用户名密码方式的认证器
 * @author xyjxust
 * @create 2022/3/8 14:09
 **/
public class UsernamePasswordAuthenticator  extends AbstractAuthenticator<UsernamePasswordCredentials>{

    private static final String USER_NAME = "username";

    private static final String PASSWORD = "password";


    /**
     * 提取登录凭证相关信息
     * @param webContextHolder
     * @return
     */
    @Override
    public Optional<UsernamePasswordCredentials> doGetCredentials(WebContextHolder webContextHolder) {
        String body =  webContextHolder.getRequestContent().orElseThrow(()->new IllegalArgumentException("未传输认证参数"));
        Map<String,String> params = JsonUtils.toObject(body, Map.class);
        if(params==null||params.size()==0){
            throw new IllegalArgumentException("未传输认证参数");
        }
        String username = Optional.ofNullable(params.get(USER_NAME)).orElseThrow(()->  new IllegalArgumentException("用户名不能为空"));
        String password = Optional.ofNullable(params.get(PASSWORD)).orElseThrow(()->  new IllegalArgumentException("密码不能为空"));
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials();
        usernamePasswordCredentials.setUsername(username);
        usernamePasswordCredentials.setPassword(password);
        return Optional.of(usernamePasswordCredentials);
    }

    @Override
    public Optional<UserDetails> doAuthenticate(UsernamePasswordCredentials credentials, WebContextHolder webContextHolder) {
        UserDetails userDetails = userDetailService.loadUserByUsername(credentials.getUsername());
        return Optional.ofNullable(userDetails);
    }

    @Override
    public String getType() {
        return AuthConstant.DEFAULT_AUTH_TYPE;
    }
}
